package com.stars.easyms.alarm.client.email;

import com.stars.easyms.alarm.client.BaseEasyMsAlarmClient;
import com.stars.easyms.alarm.client.EasyMsAlarmChannel;
import com.stars.easyms.alarm.message.EasyMsAlarmMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.mail.HtmlEmail;

import java.util.stream.Stream;

/**
 * <p>className: EasyMsEmailAlarmClient</p>
 * <p>description: EasyMsEmail告警客户端</p>
 *
 * @author guoguifang
 * @version 1.7.0
 * @date 2020/11/26 4:36 下午
 */
@Slf4j
public class EasyMsEmailAlarmClient extends BaseEasyMsAlarmClient {

    private String host;

    private String port;

    private String sslPort;

    private String fromUser;

    private String token;

    private String[] toUsers;

    EasyMsEmailAlarmClient(EasyMsAlarmChannel easyMsAlarmChannel, String id, String host, String port, String sslPort,
                           String fromUser, String token, String toUser) {
        super(easyMsAlarmChannel, id);
        this.host = host;
        this.port = port;
        this.sslPort = sslPort;
        this.fromUser = fromUser;
        this.token = token;
        this.toUsers = Stream.of(toUser.split(",")).map(String::trim).toArray(value -> new String[0]);
    }

    EasyMsEmailAlarmClient(EasyMsAlarmChannel easyMsAlarmChannel, String host, String port, String sslPort,
                           String fromUser, String token, String toUser) {
        this(easyMsAlarmChannel, null, host, port, sslPort, fromUser, token, toUser);
    }

    @Override
    public void sendAlarmMessage(EasyMsAlarmMessage alarmMessage) throws Exception {
        HtmlEmail htmlEmail = new HtmlEmail();
        htmlEmail.setCharset("UTF-8");
        htmlEmail.setHostName(host);

        htmlEmail.setAuthentication(fromUser, token);
        htmlEmail.setFrom(fromUser);
        htmlEmail.addTo(toUsers);
        htmlEmail.setSubject(alarmMessage.getTitle());
        htmlEmail.setTextMsg(alarmMessage.getContext());
        if (StringUtils.isNotBlank(sslPort)) {
            htmlEmail.setSslSmtpPort(sslPort);
            htmlEmail.setSSLOnConnect(true);
            htmlEmail.setSSLCheckServerIdentity(true);
        } else {
            htmlEmail.setSmtpPort(Integer.parseInt(port));
        }
        String result = htmlEmail.send();
        if (log.isDebugEnabled()) {
            log.debug("email sendMsg success:" + result);
        }
    }

}
